﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;

namespace Jenvin.Library.Threading
{
    public static class AsyncExtensions
    {
        #region System Extensions

        public static Async<WebResponse> GetResponseAsync(this WebRequest req)
        {
            return new AsyncPrimitive<WebResponse>(req.BeginGetResponse, req.EndGetResponse);
        }

        public static Async<int> ReadAsync(this Stream stream, byte[] buffer, int offset, int count)
        {
            return new AsyncPrimitive<int>(
                (callback, st) => stream.BeginRead(buffer, offset, count, callback, st),
                stream.EndRead);
        }

        public static IEnumerable<IAsync> ReadToEndAsync(this Stream stream)
        {
            MemoryStream ms = new MemoryStream();
            int read = -1;
            while (read != 0)
            {
                byte[] buffer = new byte[1024];
                Async<int> count = stream.ReadAsync(buffer, 0, 1024);
                yield return count;

                Console.WriteLine("[{0}] got data: {1}", "url", count.Result);
                ms.Write(buffer, 0, count.Result);
                read = count.Result;
            }

            ms.Seek(0, SeekOrigin.Begin);
            string s = new StreamReader(ms).ReadToEnd();

            //返回结果 
            yield return new Async<string>((res) => res(s));
        }

        #endregion


    }

}
